package com.share.cloudStorage.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.share.cloudStorage.admin.model.Admin;
import com.share.cloudStorage.admin.model.Params;
import com.share.cloudStorage.admin.service.AdminService;
import com.share.cloudStorage.constant.Constants;
import com.share.cloudStorage.filter.SecurityFilter;
import com.share.cloudStorage.users.model.Users;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.share.cloudStorage.model.Result;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/api/v1/admin")
@Slf4j
public class AdminController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AdminService adminService;

    //用户登录
    @PostMapping("/login")
    public Result adminLogin(@RequestBody Admin admin, HttpServletResponse response){
        String verityCode = (String)redisTemplate.opsForValue().get("adminVerityCode:" + admin.getVerityId());
        if (!verityCode.equalsIgnoreCase(admin.getVerityCode())){
            log.info("验证码是否相等{}",verityCode.equals(admin.getVerityCode()));
            response.setStatus(405);
            return Result.fail("验证码错误");
        }
        Result result;
        log.info("username:{}",admin.getUsername());
        log.info("password:{}",admin.getPassword());
        //查询条件
        QueryWrapper<Admin> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("username",admin.getUsername());
        Admin radmin = (Admin)redisTemplate.opsForValue().get("admin:" + admin.getUsername());
        if (radmin!=null){
            log.info("redis查询admin");
            result = adminService.loginHandel(radmin, response, admin.getPassword());
        }else {
            Admin selAdmin = adminService.getOne(queryWrapper);
            log.info("数据库selAdmin：{}",selAdmin);
            if(selAdmin!=null){
                redisTemplate.opsForValue().set("admin:"+selAdmin.getUsername(),selAdmin,7, TimeUnit.DAYS);
            }
            result = adminService.loginHandel(selAdmin, response, admin.getPassword());
        }
        //查询
        return result;
    }
    //创建验证码
    @RequestMapping("/createCode")
    public void createCode(HttpServletResponse response) throws IOException     {
        //生成随机数+时间戳
        int c = RandomUtil.randomInt(1, 10000);
        long timestamp = System.currentTimeMillis();
        String id = c+ timestamp + "";
        //生成一个二进制的随机验证码图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40);
        //输出流写出
        ServletOutputStream outputStream = response.getOutputStream();
        lineCaptcha.write(outputStream);
        String code = lineCaptcha.getCode();
        //将验证码id与值保存在redis中保存一分钟
        redisTemplate.opsForValue().set("adminVerityCode:"+id,code,60, TimeUnit.SECONDS);
        response.setHeader("codeId",id);
        outputStream.flush();
        outputStream.close();
    }
    //管理员去查询用户信息
    @PostMapping("/adminSearch")
    public PageInfo adminSearch(@RequestBody Params params){
        List<Users> adminsearch = adminService.adminsearch(params);
        return new PageInfo(adminsearch);
    }
    //查询管理员
    @PostMapping("/searchAdmin")
    public IPage<Admin>  searchAdmin(@RequestParam("current") Integer current,@RequestParam("pageSize") Integer pageSize,@RequestParam("queryParam") String queryParam){
        IPage<Admin> page;
        IPage<Admin> p = new Page<>(current, pageSize);
        if (queryParam != "" && queryParam != null){
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("username", queryParam);
            page = adminService.page(p,queryWrapper);
        }else {
            page=adminService.page(p);
        }
        return page;
    }
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestParam("password") String password){
        String username = SecurityFilter.adminName.get();
        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        String spassword = DigestUtil.sha256Hex(password+ Constants.SALT);
        updateWrapper.eq("username", username).set("password",spassword);
        boolean bol = adminService.update(updateWrapper);
        if (bol){
            redisTemplate.delete("admin:" + username);
            return Result.ok("修改成功");
        }
        return Result.ok("修改失败");
    }
    @GetMapping("/resetAdminPassword")
    public Result resetAdminPassword(){
        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("username", "xyf").set("password","bc955f0be71e4fcf74cf48be54e33836de09954e5a47c81808cc069eaad63af9");
        boolean bol = adminService.update(updateWrapper);
        if (bol){
            redisTemplate.delete("admin:" + "xyf");
            return Result.ok("重置成功");
        }
        return Result.fail("重置失败");
    }
    @PostMapping("/deleteAdmin")
    public Result deleteAdmin(@RequestParam("username") String username){
        String name = SecurityFilter.adminName.get();
        if (username.equals(name)){
            return Result.fail("无法删除自己");
        }
        if (username.equals("xyf")){
            return Result.fail("无法删除");
        }
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        boolean result = adminService.remove(queryWrapper);
        if (result){
            redisTemplate.delete("admin:" + username);
            return Result.ok("删除成功");
        }else {
            return Result.fail("删除失败");
        }
    }
    @PostMapping("/addAdmin")
    public Result addAdmin(@RequestBody Admin admin){
        String spassword = DigestUtil.sha256Hex(admin.getPassword()+ Constants.SALT);
        admin.setPassword(spassword);
        boolean bol = adminService.save(admin);
        if (bol){
            return Result.ok("添加成功");
        }else {
            return Result.fail("添加失败");
        }
    }
}
